<template>
  <div class="system-dept-user layout-padding">
    <splitpanes class="default-theme" @resize="paneSize = $event[0].size">
      <pane :size="15">
        <div class="system-dept-container">
          <div class="card-header">
            <el-input size="default" placeholder="输入部门名称自动搜索" clearable v-model="filterDeptText"></el-input>
          </div>
          <el-card shadow="hover" class="layout-padding-auto">
            <div class="dept-content">
              <el-tree
                  ref="deptRef"
                  :allow-drop="allowDrop"
                  :allow-drag="allowDrag"
                  :data="stateDept.datas"
                  draggable
                  :default-expand-all="false"
                  node-key="id"
                  :props="{ label: 'deptName' }"
                  :default-expanded-keys="stateDept.expandedKeys"
                  :expand-on-click-node="false"
                  :filter-node-method="filterDeptNode"
                  @node-drag-start="handleDragStart"
                  @node-drag-enter="handleDragEnter"
                  @node-drag-leave="handleDragLeave"
                  @node-drag-over="handleDragOver"
                  @node-drag-end="handleDragEnd"
                  @node-drop="handleDrop"
                  @node-click="handleDeptNode"
              >
                <template v-slot:default="{ node, data }">
                  <div class="dept-execute" @mouseover="onShow(data)" @mouseleave="onHide(data)">
										<span class="tooltip">
											<span>{{ node.label }}</span>
										</span>
                    <div v-if="data.show" class="dept-txt-execute">
                      <!-- <div class="dept-txt-execute"> -->
                      <!-- <SvgIcon name="ele-CirclePlus" :size="14" class="dept-execute-icon" @click="handleAddDeptNodeData('add', data)" />
                      <SvgIcon name="ele-Edit" :size="14" class="dept-execute-icon" />
                      <SvgIcon name="ele-Delete" :size="14" class="dept-execute-icon" /> -->
                      <el-button size="small" link type="info" @click="handleAddDeptNodeData('add', data)">添加
                      </el-button>
                      <el-button v-if="data.id !== '0'" size="small" link type="info"
                                 @click="handleAddDeptNodeData('edit', data)">修改
                      </el-button>
                      <el-button v-if="data.id !== '0'" size="small" link type="info"
                                 @click="handleAddDeptNodeData('delete', data)">删除
                      </el-button>
                    </div>
                  </div>
                </template>
              </el-tree>
            </div>
          </el-card>
        </div>
      </pane>
      <pane :size="85">
        <div class="system-user-content-container">
          <div class="standard-container system-user-container layout-padding-no-left layout-pd w100"
               style="padding: 0px 10px !important">
            <div class="review-list-title">
              <div class="title-actions">
                <el-button size="default" type="primary" class="ml10" @click="batchDelUser">
                  <el-icon>
                    <ele-FolderAdd/>
                  </el-icon>
                  批量删除
                </el-button>
                <el-button size="default" type="primary" class="ml10" @click="onOpenAddUser('add')">
                  <el-icon>
                    <ele-FolderAdd/>
                  </el-icon>
                  新增用户
                </el-button>
              </div>
            </div>
            <el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%"
                      @selection-change="handleSelectionUser">
              <el-table-column type="selection" width="55"/>
              <!-- <el-table-column type="index" label="序号" width="60" /> -->
              <el-table-column prop="username" label="用户名" show-overflow-tooltip></el-table-column>
              <el-table-column prop="nickname" label="用户昵称" show-overflow-tooltip></el-table-column>
              <!-- <el-table-column prop="roleSign" label="关联角色" show-overflow-tooltip></el-table-column> -->
              <!-- <el-table-column prop="department" label="部门" show-overflow-tooltip></el-table-column> -->
              <el-table-column prop="mobile" label="手机号" show-overflow-tooltip></el-table-column>
              <el-table-column prop="email" label="邮箱" show-overflow-tooltip></el-table-column>
              <el-table-column prop="userStatus" label="用户状态" show-overflow-tooltip>
                <template #default="scope">
                  <el-tag type="success" v-if="scope.row.userStatus == 0">启用</el-tag>
                  <el-tag type="info" v-else>禁用</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="birthday" label="出生时间" show-overflow-tooltip></el-table-column>
              <el-table-column prop="expiration" label="过期时间" show-overflow-tooltip></el-table-column>
              <!-- <el-table-column prop="describe" label="用户描述" show-overflow-tooltip></el-table-column> -->
              <!-- <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip></el-table-column> -->
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button size="small" text type="primary"
                             @click="onOpenEditUser('edit', scope.row)"
                  >修改
                  </el-button
                  >
                  <el-button size="small" text type="primary"
                             @click="onRowDel(scope.row)">删除
                  </el-button>
                  <el-button size="small" text type="primary"
                             @click="onResetPassword(scope.row)"
                  >重置密码
                  </el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                  @size-change="onHandleSizeChange"
                  @current-change="onHandleCurrentChange"
                  :pager-count="15"
                  :page-sizes="[10, 15, 20, 30, 50, 100]"
                  v-model:current-page="state.tableData.paging.currentPage"
                  background
                  v-model:page-size="state.tableData.paging.pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="state.tableData.paging.totalCount"
              >
              </el-pagination>
            </div>
          </div>
        </div>
      </pane>
    </splitpanes>

    <UserDialog ref="userDialogRef" @refresh="getTableData()"/>
    <DeptDialog ref="deptDialogRef" @refreshDept="refreshDept()"></DeptDialog>
  </div>
</template>

<script setup lang="ts" name="systemUser">
import {defineAsyncComponent, reactive, onMounted, ref, watch} from 'vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import {Splitpanes, Pane} from 'splitpanes';
import type Node from 'element-plus/es/components/tree/src/model/node';
import type {DragEvents} from 'element-plus/es/components/tree/src/model/useDragNode';
import type {AllowDropType, NodeDropType} from 'element-plus/es/components/tree/src/tree.type';
import 'splitpanes/dist/splitpanes.css';
import {userApi} from '/@/api/sys/user/index';
import {deptApi} from '/@/api/sys/dept/index';
import msg from '/@/utils/messageUtils';
// 引入组件
const UserDialog = defineAsyncComponent(() => import('/@/views/system/user/dialog.vue'));
const DeptDialog = defineAsyncComponent(() => import('/@/views/system/user/deptDialog.vue'));
const paneSize = ref(50);
// 定义变量内容
const userDialogRef = ref();
const deptDialogRef = ref();
const tableSearchRef = ref();
// const
const deptRef = ref();

const filterDeptText = ref('');
const state = reactive({
  isToggle: false,
  tableData: {
    data: [],
    total: 0,
    loading: false,
    paging: {
      currentPage: 1,
      pageSize: 15,
      totalCount: 0,
      totalPages: 0,
    },
  },
});

const stateSearchUser = reactive({
  deptId: '',
  username: '',
  userStatus: '',
  mobile: '',
});

const stateDept = reactive({
  datas: [],
  expandedKeys: ['0'],
  title: '新增部门',
  search: '',
});

const choiceUser = reactive({
  ids: [],
});
const onReset = (formEl: any) => {
  if (!formEl) return;
  formEl.resetFields();
};

const handleSearchUser = () => {
  state.tableData.paging.currentPage = 1;
  getTableData();
};

const handleSelectionUser = (users: any) => {
  choiceUser.ids = [];
  users.forEach((u: any) => {
    choiceUser.ids.push(u.id);
  });
};

const batchDelUser = () => {
  console.log('userIds: ', JSON.stringify(choiceUser.ids));
  if (choiceUser.ids.length < 1) {
    msg().warn('请至少选中一个用户');
    return;
  }
  ElMessageBox.confirm(`此操作将永久选中的用户，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        try {
          await userApi().batchDeleteUser({
            userIds: choiceUser.ids,
          });
          state.tableData.paging.currentPage = 1;
          getTableData();
          msg().success('批量删除成功');
        } catch (error) {
          msg().error('批量删除失败');
        }
      })
      .catch(() => {
      });
};

// 初始化表格数据
const getTableData = async () => {
  state.tableData.loading = true;
  try {
    const {data} = await userApi().searchUser({
      offset: (state.tableData.paging.currentPage - 1) * state.tableData.paging.pageSize,
      limit: state.tableData.paging.pageSize,
      deptId: stateSearchUser.deptId,
      username: stateSearchUser.username,
      userStatus: stateSearchUser.userStatus,
      mobile: stateSearchUser.mobile,
    });
    state.tableData.data = data.datas;
    state.tableData.paging.currentPage = data.paging.currentPage;
    state.tableData.paging.totalCount = data.paging.totalCount;
  } catch (error) {
    msg().error('查询失败，请稍后重试');
  }

  state.tableData.loading = false;
};
// 打开新增用户弹窗
const onOpenAddUser = (type: string) => {
  userDialogRef.value.openDialog(type);
};
// 打开修改用户弹窗
const onOpenEditUser = (type: string, row: RowUserType) => {
  userDialogRef.value.openDialog(type, row);
};

// 删除用户
const onRowDel = (row: RowUserType) => {
  ElMessageBox.confirm(`此操作将永久删除账户名称：“${row.username}”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        try {
          await userApi().deleteUser(row.id);
          state.tableData.paging.pageSize = 15;
          state.tableData.paging.currentPage = 1;
          getTableData();
          msg().success('删除成功');
        } catch (error) {
          msg().error('删除用户失败,请重试...');
        }
      })
      .catch(() => {
      });
};

const onResetPassword = async (row: RowUserType) => {

  try {
    const {data} = await userApi().resetPassword({
      id: row.id,
    });

    ElMessageBox.alert(data, '新密码', {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: '确认',
    })

  } catch (error) {
    msg().error('重置密码失败， 稍后重试');
  }

};
// 分页改变
const onHandleSizeChange = (val: number) => {
  // state.tableData.param.pageSize = val;
  // console.log('onHandleSizeChange: ', val);
  state.tableData.paging.pageSize = val;
  state.tableData.paging.currentPage = 1;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
  // state.tableData.param.pageNum = val;
  // console.log('onHandleCurrentChange: ', val);
  getTableData();
};

const onLoadDeptTree = async () => {
  try {
    const {data} = await deptApi().tree();
    stateDept.datas = data;
  } catch (error) {
    msg().error('查询部门失败,请重试!');
  }
};

watch(filterDeptText, (val) => {
  deptRef.value!.filter(val);
});

const filterDeptNode = (value: string, data: any) => {
  console.log('data: ', data);
  if (!value) return true;
  return data.deptName.includes(value);
};

// 页面加载时
onMounted(() => {
  getTableData();
  onLoadDeptTree();
});

const refreshDept = () => {
  // console.log('部门操作完成');
  onLoadDeptTree();
};

const handleDragStart = (node: Node) => {
  // console.log('drag start', node);
};
const handleDragEnter = (draggingNode: Node, dropNode: Node) => {
  // console.log('tree drag enter:', dropNode.label);
};
const handleDragLeave = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {
  // console.log('tree drag leave:', dropNode.label);
};
const handleDragOver = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {
  // console.log('tree drag over:', dropNode.label);
};
const handleDragEnd = (draggingNode: Node, dropNode: Node, dropType: NodeDropType, ev: DragEvents) => {
  // console.log('tree drag end:', dropNode && dropNode.label, dropType);
};
const handleDrop = async (draggingNode: Node, dropNode: Node, dropType: NodeDropType, ev: DragEvents) => {
  // console.log('tree drop:', dropNode.label, dropType);
  // console.log('handleDrop---draggingNode: ', draggingNode.data.deptName, ' , draggingNode.data.id: ', draggingNode.data.id);
  // console.log('handleDrop---dropNode: ', dropNode.data.deptName, ' , dropNode.data.id: ', dropNode.data.id);
  // console.log('type: ', dropType);

  try {
    await deptApi().changeParent({
      id: draggingNode.data.id,
      parentId: dropNode.data.id,
    });
  } catch (error) {
    msg().error('移动部门失败,请重试');
  }
};
const allowDrop = (draggingNode: Node, dropNode: Node, type: AllowDropType) => {
  // console.log('allowDrop---draggingNode: ', draggingNode.data.deptName, ' , draggingNode.data.id: ', draggingNode.data.id);
  // console.log('allowDrop---dropNode: ', dropNode.data.deptName, ' , dropNode.data.id: ', dropNode.data.id);
  // console.log('type: ', type);
  if (dropNode.data.id === '0') {
    return type !== 'next' && type !== 'prev';
  } else {
    return type === 'inner';
  }
};

const allowDrag = (draggingNode: Node) => {
  // console.log('draggingNode: ', draggingNode.data.deptName, ' , draggingNode.data.id: ', draggingNode.data.id);
  return draggingNode.data.id !== '0';
};

const handleDeptNode = (node: any) => {
  if (node.id !== stateSearchUser.deptId) {
    stateSearchUser.deptId = node.id;
    state.tableData.paging.currentPage = 1;
    getTableData();
  }
};

const handleAddDeptNodeData = (type: string, data: any) => {
  console.log('type: ', type);
  if (type === 'delete') {
    ElMessageBox.confirm(`此操作将永久删除部门名称：“${data.deptName}”，是否继续?`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
        .then(async () => {
          try {
            await deptApi().deleteDept(data.id);
            msg().success('删除成功');
            onLoadDeptTree();
          } catch (error) {
            msg().error('删除部门失败....');
          }
        })
        .catch(() => {
        });
  } else {
    if (type === 'edit') {
      console.log('edit: ', type);
      // stateDept.title = '更新部门';
      deptDialogRef.value.openDialog('edit', data);
    } else {
      console.log('add: ', type);
      // stateDept.title = '新增部门';
      deptDialogRef.value.openDialog('add', data);
    }
  }
};

const onShow = (data: any) => {
  data.show = true;
};

const onHide = (data: any) => {
  data.show = false;
};
</script>

<style scoped lang="scss">
.system-dept-user {
  padding: 15px !important;
  overflow: hidden;
  height: calc(100vh - 84px);

  .system-dept-container {
    height: 100%;

    :deep(.el-card__body) {
      display: flex;
      flex-direction: column;
      flex: 1;
      overflow: auto;
      margin: 15px 15px 40px 15px;
      padding: 0px;
    }

    :deep(.el-tree-node__content) {
      // display: block !important;
    }
  }

  .system-user-container {
    .el-table {
      flex: 1;
      width: 100%;
    }
  }

  .dept-execute {
    width: 100%;
  }

  .dept-txt-execute {
    display: inline-block;
    // padding: 0px 5px;
    // margin-left: 5px;
    color: #777777;
    // 	display: inline-block;
    // 	height: 20px;
    // 	line-height: 20px;
    .dept-execute-icon {
      margin: 0px 3px;
    }
  }
}

.tooltip {
  margin-right: 5px;
  font-size: 13px;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
  padding: 4px;
}

.splitpanes__pane {
  // justify-content: center;
  // align-items: center;
  // display: flex;
  // position: relative;
  // font-size: 70px;
  // color: var(--el-color-primary-light-5);
  // border: 1px solid var(--el-border-color-lighter);
  // background-color: var(--el-color-primary) !important;
}

.splitpanes--horizontal {
  .splitpanes__splitter {
    padding: 15px 0 0 0 !important;
  }
}

.system-user-content-container {
  height: 100%;
  width: 100%;
  position: relative;
}
</style>
